import img1 from '../11.17-红绿灯/img/1.jpeg';
import img2 from '../11.17-红绿灯/img/2.jpeg';
import img3 from '../11.17-红绿灯/img/3.jpeg';
let arr = [img1, img2, img3];
// 面向对象 / 面向过程

// 定义一个红绿灯类（构造函数）
function Light($box) {
    //装红绿灯的容器
    this.box = document.querySelector($box);
    // 初始值
    this.index = 1;
}

// 初始化图片的方法
Light.prototype.init = function () {
    console.log('初始化图片');
    // 创建图片标签
    this.img = new Image();
    // 图片设置不可拖拽
    this.img.draggable = false;
    // debugger 在页面上自动加上断点
    // debugger;
    this.img.src = `${arr[this.index - 1]}`;
    let time1;
    time1 = setInterval(function () {
        this.index++;
    }, 100);
    console.log(time1);
    // 添加到容器中
    this.box.appendChild(this.img);
    // 初始化完成之后绑定点击事件
    this.bindClick();
};

// 绑定点击事件
Light.prototype.bindClick = function () {
    this.img.addEventListener('click', () => {
        // this.index++;
        this.index = (this.index % 3) + 1;
        // 判断图片是否超过 1-3
        // this.index > 3 && (this.index = 1);
        this.img.src = `${arr[this.index - 1]}`;
    });
};
console.log(Light.prototype);

//绑定自动轮播事件
Light.prototype.autoPlay = function () {
    let time1;
    // clearInterval(time1)
    time1 = setInterval(() => {
        this.index++;
        this.index > 3 && (this.index = 1);
        this.img.src = `${arr[this.index]}`;
        console.log(this.index);
    }, 1000);

    this.img.addEventListener('mouseenter', () => {
        clearInterval(time1);
    });
    this.img.addEventListener('mouseleave', () => {
        time1 = setInterval(() => {
            this.index = (this.index % 3) + 1;
            console.log(arr);
            this.img.src = `${arr[this.index - 1]}`;
        }, 1000);
    });
};

// 绑定点击上下事件
Light.prototype.updownClick = function () {
    let flag = true;
    let timer2;
    timer2 = setInterval(() => {
        if (flag) this.index++;
        if (!flag) this.index--;
        if (this.index == 3) flag = false;
        if (this.index == 1) flag = true;
        this.img.src = `${arr[this.index - 1]}`;
    }, 1000);
    this.img.addEventListener('mouseenter', () => {
        clearInterval(timer2);
    });
    this.img.addEventListener('mouseleave', () => {
        timer2 = setInterval(() => {
            if (flag) this.index++;
            if (!flag) this.index--;
            if (this.index == 3) flag = false;
            if (this.index == 1) flag = true;
            this.img.src = `${arr[this.index - 1]}`;
        }, 1000);
    });
};

let l1 = new Light('.box1');
l1.init();
let l2 = new Light('.box2');
l2.init();
l2.autoPlay();
let l3 = new Light('.box3');
l3.init();
l3.updownClick();
